﻿using SheepStorage.Domain.Entity;
using SheepStorage.Domain.lishunEnum;
using SheepStorage.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
using SheepStorage.Service.Interface;
using SheepStorage.Domain.DTO.InputDto;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Enum;
using Microsoft.EntityFrameworkCore;

namespace SheepStorage.Service.DataImp
{
    /// <summary>
    /// 羊只档案
    /// </summary>
    public class SheepRecordService : ISheepRecordService
    {
        IBaseRepository<SheepRecord> _srres;
        IBaseRepository<BuildingManagement> _bmres;
        IBaseRepository<SheepField> _sfres;
        IBaseRepository<EarTagTable> _eares;

        public SheepRecordService(IBaseRepository<SheepRecord> srres, IBaseRepository<BuildingManagement> bmres,
            IBaseRepository<SheepField> sfres, IBaseRepository<EarTagTable> eares)
        {
            _srres = srres;
            _bmres = bmres;
            _sfres = sfres;
            _eares = eares;
        }

        //添加
        public async Task<int> AddSheepRecord(SheepRecord input)
        {
            if (input.AddTime == null)
            {
                input.AddTime = DateTime.Now;
            }
            input.IsDel = false;
            var list = _srres.Add(input);

            if (list > 0)
            {
                var id = _eares.GetAll().FirstOrDefault(x => x.OverBit == input.OverBit);
                id.UseState = 2;
                _eares.Update(id);
            }

            return list;
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<SheepRecord> ShowSheepRecordDTO(int ids)
        {
            var list = _srres.GetAll().FirstOrDefault(x => x.SheepRecordId == ids);
            
            return list;
        }

        /// <summary>
        /// 查询显示
        /// </summary>
        /// <param name="sheepRecordInput"></param>
        /// <param name="totalCount"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public async Task<List<SheepRecordOutput>> GetSheepRecord(SheepRecordInput sheepRecordInput)
        {

            var list = (from a in _srres.GetAll().Where(x=>x.IsDel==false)
                        select new SheepRecordOutput
                        {
                            SheepRecordId = a.SheepRecordId,
                            OverBit = a.OverBit,
                            ElEarTag = a.ElEarTag,
                            SheepRecordVariety = (SheepRecordVarietyEnum)a.SheepRecordVariety,
                            SheepRecordSex = a.SheepRecordSex,
                            SheepRecordBirthDate = a.SheepRecordBirthDate,
                            SheepRecordDay = a.SheepRecordDay,
                            SheepRecordMoom = a.SheepRecordMoom,
                            SheepRecordGrowth = (SheepRecordGrowthEnum)a.SheepRecordGrowth,
                            BuildingName = a.BuildingName,
                            SheepFieldName = a.SheepFieldName,
                            SheepRecordType = (SheepRecordTypeEnum)a.SheepRecordType,
                            SheepRecordGene = (SheepRecordGeneEnum)a.SheepRecordGene,
                            SheepRecordProduction = (SheepRecordProductionEnum)a.SheepRecordProduction,
                            SheepRecordMarket = (SheepRecordMarketEnum)a.SheepRecordMarket,
                            SheepRecordBreedState = (SheepRecordBreedStateEnum)a.SheepRecordBreedState,
                            SheepRecordBreedDay = a.SheepRecordBreedDay,
                            SheepRecordDadOverbit = a.SheepRecordDadOverbit,
                            SheepRecordMomOverbit = a.SheepRecordMomOverbit,
                            SheepRecordPresentState = (SheepRecordPresentStateEnum)a.SheepRecordPresentState,
                            SheepRecordGestation = a.SheepRecordGestation,
                            SheepRecordWeightBirth = a.SheepRecordWeightBirth,
                            SheepRecordWeaningWeight = a.SheepRecordWeaningWeight,
                            SheepRecordWeaningDate = a.SheepRecordWeaningDate,
                            SheepRecordWeaningAge = a.SheepRecordWeaningAge,
                            SheepRecordRemark = a.SheepRecordRemark,
                            SheepRecordBirthState = (SheepRecordBirthStateEnum)a.SheepRecordBirthState
                        }).ToList();
            if (!string.IsNullOrEmpty(sheepRecordInput.OverBit))
            {
                list = list.Where(x => x.OverBit != null&& x.OverBit.Contains(sheepRecordInput.OverBit)).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.ElEarTag))
            {
                list = list.Where(x => x.ElEarTag!=null && x.ElEarTag.Contains(sheepRecordInput.ElEarTag)).ToList();
            }
            if (sheepRecordInput.SheepRecordVariety > 0)
            {
                list = list.Where(x => x.SheepRecordVariety == (SheepRecordVarietyEnum)sheepRecordInput.SheepRecordVariety).ToList();
            }
            if (sheepRecordInput.SheepRecordSex != null)
            {
                list = list.Where(x => x.SheepRecordSex == sheepRecordInput.SheepRecordSex).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.staSheepRecordBirthDate))
            {
                list = list.Where(x => x.SheepRecordBirthDate >= DateTime.Parse(sheepRecordInput.staSheepRecordBirthDate)).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.endSheepRecordBirthDate))
            {
                list = list.Where(x => x.SheepRecordBirthDate <= DateTime.Parse(sheepRecordInput.endSheepRecordBirthDate)).ToList();
            }
            if (sheepRecordInput.staSheepRecordMoom > 0)
            {
                list = list.Where(x => x.SheepRecordMoom >= sheepRecordInput.staSheepRecordMoom).ToList();
            }
            if (sheepRecordInput.endSheepRecordMoom > 0)
            {
                list = list.Where(x => x.SheepRecordMoom <= sheepRecordInput.endSheepRecordMoom).ToList();
            }
            if (sheepRecordInput.SheepRecordGrowth > 0)
            {
                list = list.Where(x => x.SheepRecordGrowth == (SheepRecordGrowthEnum)sheepRecordInput.SheepRecordGrowth).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.BuildingName))
            {
                list = list.Where(x => x.BuildingName == sheepRecordInput.BuildingName).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.SheepFieldName))
            {
                list = list.Where(x => x.SheepFieldName == sheepRecordInput.SheepFieldName).ToList();
            }
            if (sheepRecordInput.SheepRecordType > 0)
            {
                list = list.Where(x => x.SheepRecordType == (SheepRecordTypeEnum)sheepRecordInput.SheepRecordType).ToList();
            }
            if (sheepRecordInput.SheepRecordGene > 0)
            {
                list = list.Where(x => x.SheepRecordGene == (SheepRecordGeneEnum)sheepRecordInput.SheepRecordGene).ToList();
            }
            if (sheepRecordInput.SheepRecordProduction > 0)
            {
                list = list.Where(x => x.SheepRecordProduction == (SheepRecordProductionEnum)sheepRecordInput.SheepRecordProduction).ToList();
            }
            if (sheepRecordInput.SheepRecordMarket > 0)
            {
                list = list.Where(x => x.SheepRecordMarket == (SheepRecordMarketEnum)sheepRecordInput.SheepRecordMarket).ToList();
            }
            if (sheepRecordInput.SheepRecordBreedState > 0)
            {
                list = list.Where(x => x.SheepRecordBreedState == (SheepRecordBreedStateEnum)sheepRecordInput.SheepRecordBreedState).ToList();
            }
            if (sheepRecordInput.staSheepRecordBreedDay > 0)
            {
                list = list.Where(x => x.SheepRecordBreedDay >= sheepRecordInput.staSheepRecordBreedDay).ToList();
            }
            if (sheepRecordInput.endSheepRecordBreedDay > 0)
            {
                list = list.Where(x => x.SheepRecordBreedDay <= sheepRecordInput.endSheepRecordBreedDay).ToList();
            }
            if (!string.IsNullOrEmpty(sheepRecordInput.SheepRecordDadOverbit))
            {
                list = list.Where(x => x.SheepRecordDadOverbit!=null && x.SheepRecordDadOverbit.Contains(sheepRecordInput.SheepRecordDadOverbit)).ToList();
            }
            if (sheepRecordInput.SheepRecordPresentState > 0)
            {
                list = list.Where(x => x.SheepRecordPresentState == (SheepRecordPresentStateEnum)sheepRecordInput.SheepRecordPresentState).ToList();
            }
            list = list.OrderByDescending(x => x.SheepRecordId).Skip((sheepRecordInput.pageIndex - 1) * sheepRecordInput.pageSize).Take(sheepRecordInput.pageSize).ToList();
            return list;
        }

        /// <summary>
        /// 批删
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DelSheepRecord(string? ids)
        {
            // 分割ID字符串
            var idArray = ids.Split(',', StringSplitOptions.RemoveEmptyEntries);
            // 转换为整数数组
            var sheepRecordIds = idArray.Select(id =>
            {
                if (!int.TryParse(id, out int result))
                {
                    throw new ArgumentException($"无效的羊记录ID: {id}");
                }
                return result;
            }).ToList();
            var list = _srres.GetAll().Where(x => sheepRecordIds.Contains(x.SheepRecordId)).ToList();
     
            foreach(var item in list)
            {
                item.DelTime= DateTime.Now;
                item.IsDel = true;
            }
            var li = _srres.UpdateRange(list);
            return li;
        }

        /// <summary>
        /// 根据栋舍名称查询栋舍id
        /// </summary>
        /// <param name="buildingManagementName"></param>
        /// <returns></returns>
        public int MyGetSheepField(string buildingManagementName)
        {
            var list=_bmres.GetAll().FirstOrDefault(x=>x.BuildingName==buildingManagementName).BuildingManagementId;
            return list;
        }


        /// <summary>
        /// 种母查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<SheepRecord> ShowSheepMom()
        {
            return _srres.GetAll().Where(x => x.SheepRecordType == 2 && x.IsDel==false).ToList();
        }
        /// <summary>
        /// 种公查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<SheepRecord> ShowSheepDad()
        {
            return _srres.GetAll().Where(x =>x.SheepRecordType == 1 && x.IsDel == false).ToList();
        }

        /// <summary>
        /// 修改繁殖状态
        /// </summary>
        /// <param name="OverBitTolist"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepRecordBreedState(string OverBitTolist, int state)
        {
            var OverBit = OverBitTolist.Split(',');
            var list = _srres.GetAll().Where(x => OverBit.Contains(x.OverBit)).ToList();
            foreach(var item in list)
            {
                item.SheepRecordBreedState = state;
                item.UpdateTime= DateTime.Now;
            }
            var upd = _srres.UpdateRange(list);
            return upd;
        }


        /// <summary>
        /// 修改当前栋舍和栏位
        /// </summary>
        /// <param name="OverBitTolist"></param>
        /// <param name="BuildingId"></param>
        /// <param name="SheepFieldId"></param>
        /// <returns></returns>
        public async Task<int> UpdateNewBuilding(string OverBitTolist, int BuildingId, int SheepFieldId)
        {
            var list = _srres.GetAll().Where(x => OverBitTolist.Contains(x.OverBit)).ToList();
            foreach(var item in list)
            {
                item.BuildingName = _bmres.GetAll().FirstOrDefault(x => x.BuildingManagementId == BuildingId).BuildingName;
                item.SheepFieldName = _sfres.GetAll().FirstOrDefault(x => x.SheepFieldId == SheepFieldId).SheepFieldName;
            }
            return _srres.UpdateRange(list);
        }


        /// <summary>
        /// 根据繁殖状态查羊只档案的数据
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<List<SheepRecord>> SheepRecordList(int recordType, int breedState, int presentState,int growState)
        {
            var list = _srres.GetAll().Where(c => c.IsDel == false).ToList();

            if (recordType != 0)
            {
                list = list.Where(c => c.SheepRecordType == recordType).ToList();
            }

            if (breedState != 0)
            {
                list = list.Where(c => c.SheepRecordBreedState == breedState).ToList();
            }

            if (presentState != 0)
            {
                list = list.Where(c => c.SheepRecordPresentState == presentState).ToList();
            }

            if (growState != 0)
            {
                list = list.Where(c => c.SheepRecordGrowth == growState).ToList();
            }


            return list;

        }

        /// <summary>
        /// 修改羊只档案
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepRecord(SheepRecord input)
        {
            var list = _srres.Update(input);
            return list;
        }

        /// <summary>
        /// 根据耳号查找羊只档案
        /// </summary>
        /// <param name="ov"></param>
        /// <returns></returns>
        public SheepRecord GetDs(string ov)
        {
            var list = _srres.GetAll().FirstOrDefault(x => x.OverBit == ov);
            return list;
        }

        public async Task<List<SheepRecord>> GetSheepRecordAll()
        {
            var list = _srres.GetAll().ToList();
            return list;
        }
    }
}
